package com.lg.erp.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lg.erp.entity.*;
import com.lg.erp.service.IRoleService;
import com.lg.erp.service.IUserRoleService;
import com.lg.erp.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ligen
 * @since 2021-04-12
 */
@RestController
public class UserRoleController {

    @Autowired
    private IUserRoleService userRoleService;
    @Autowired
    private IRoleService roleService;

    @RequestMapping("/role/user/{id}")
    public JsonResult getUserRole(@PathVariable String id){
        List<SUserRole> list = userRoleService.list(new QueryWrapper<SUserRole>().lambda()
                .eq(SUserRole::getUserId, id));
        List<String> listOfRoleName=new ArrayList<>();
        for (SUserRole userRole : list) {
            SRole byId = roleService.getById(userRole.getRoleId());
           listOfRoleName.add(byId.getRoleName());
        }
        System.out.println(listOfRoleName);
        return new JsonResult(1,id,listOfRoleName);
    }

    @PostMapping("/role/user/{roleId}/{userId}")
    public JsonResult updateUserRole(@PathVariable("roleId") String roleId,@PathVariable("userId") String userId){
        SUserRole one = userRoleService.getOne(new QueryWrapper<SUserRole>().lambda()
                .eq(SUserRole::getUserId, userId).eq(SUserRole::getRoleId, roleId));
        SRole byId = roleService.getById(roleId);
        if (one==null){
            SUserRole userRole = new SUserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);
            userRoleService.save(userRole);
        }else{
            userRoleService.remove(new QueryWrapper<SUserRole>().lambda()
                    .eq(SUserRole::getRoleId,one.getRoleId())
                    .eq(SUserRole::getUserId,one.getUserId()));
        }
        List<SUserRole> list = userRoleService.list(new QueryWrapper<SUserRole>().lambda()
                .eq(SUserRole::getUserId, userId));
        List<String> listOfRoleName=new ArrayList<>();
        for (SUserRole i : list) {
            SRole roleServiceById = roleService.getById(i.getRoleId());
            listOfRoleName.add(roleServiceById.getRoleName());
        }
        return new JsonResult(1,"ok",listOfRoleName);
    }
}
